﻿using NfsBLL;
using NfsCommon.Export;
using NfsCommon.UpoadHepler;
using NfsCommon.Util;
using NfsModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace ManagerWed.Controllers
{
    public class AgencyController : Controller
    {
        //
        // GET: /Agency/
        public ActionResult Agency()
        {

            ViewData["hiden_type"] = CookieHelper.GetDecodeCookie("pcnfs_type");
            return View();
        }
        #region 编辑绑定文本信息
        public JsonResult GetAgency(int id)
        {
             
                    AgencyBLL bll = new AgencyBLL();
                    agency model = bll.GetModel(id);
                    if (model != null)
                    {
                        account act = new AccountBLL().GetModel((int)model.account_id);
                        return Json(new { MessageCode = "0", model = model, pwd = act != null ? act.user_pwd : "" }, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(new { MessageCode = "200" }, JsonRequestBehavior.AllowGet);

                    }
        }
        #endregion

        #region PC模糊查询
        public JsonResult queryagency(int pageindex, int pagesize, int keys, string keyName, int category_id, string zhuangtai)
        {
            try
            {
                AgencyBLL bll = new AgencyBLL();
                List<agency> list = bll.GetAgencyBycondtion(pageindex, pagesize, keys, keyName, category_id, zhuangtai);
                object pagecount = bll.GetAgencyBycondtionCount(keys, keyName, category_id, zhuangtai);
                return Json(new { MessageCode = "0", Agencylist = list, Pagecount = (int.Parse(pagecount.ToString()) + pagesize - 1) / pagesize }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {

                return Json(new { MessageCode = "200" }, JsonRequestBehavior.AllowGet);

            }

        }
        #endregion

        #region 通过和不通过当前登录人的下级申请
        [HttpPost]
        public JsonResult OpeaAgencys()
        {
            try
            {
                string opea = Request["opea"] != null ? Request["opea"] : "";
                int id = Request["id"] != null ? int.Parse(Request["id"].ToString()) : 0;
                string Name = Request["Name"] != null ? Request["Name"] : "";
                string companyName = Request["companyName"] != null ? Request["companyName"] : "";
                string contract_name = Request["contract_name"] != null ? Request["contract_name"] : "";
                string mobile = Request["mobile"] != null ? Request["mobile"] : "";
                string qq = Request["qq"] != null ? Request["qq"] : "";
                string wxOpenid = Request["wxOpenid"] != null ? Request["wxOpenid"] : "";
                string wwCode = Request["wwCode"] != null ? Request["wwCode"] : "";
                string idCard = Request["idCard"] != null ? Request["idCard"] : "";
                string shopUrl = Request["shopUrl"] != null ? Request["shopUrl"] : "";
                int category_id = Request["category_id"] != null ? int.Parse(Request["category_id"]) : 0;
                int level_id = Request["level_id"] != null ? int.Parse(Request["level_id"]) : 0;
                string level_name = Request["level_name"] != null ? Request["level_name"] : "";
                DateTime start_time = Request["start_time"] != null ? DateTime.Parse(Request["start_time"]) : DateTime.Parse("1991-01-01");
                int state = Request["state"] != null ? int.Parse(Request["state"].ToString()) : 1;
                DateTime end_time = start_time.AddDays(90);

                AgencyBLL bll = new AgencyBLL();
                if (!bll.GetSingle(id, Name, mobile, qq, wxOpenid, wwCode, idCard, shopUrl))
                {

                    LevelBLL lebll = new LevelBLL();
                    AuthorizationBLL aubll = new AuthorizationBLL();
                    AccountBLL act_bll = new AccountBLL();
                    int result = 0;
                    int maxid;
                    bool fa;
                    if (opea == "add")
                    {
                        account act_model = new account { user_name = mobile, user_pwd = mobile.Substring(5, 6), type = 2, IsAdmin = 0, mobile = mobile, valid = 1, time = DateTime.Now };

                        fa = act_bll.Add(act_model, out result);
                        maxid = act_bll.GetMaxId() - 1;
                    }
                    else
                    {
                        agency ag = bll.GetModel(id);
                        account act_model = new account { id = (int)ag.account_id, user_name = mobile, user_pwd = mobile.Substring(5, 6), type = 2, IsAdmin = 0, mobile = mobile, valid = 1, time = DateTime.Now };

                        fa = act_bll.Update(act_model);
                        maxid = (int)ag.account_id;
                    }
                    if (fa)
                    {

                        agency model = new agency();
                        model.id = id;
                        model.account_id = maxid;
                        model.name = Name;
                        model.company_name = companyName;
                        model.contract_name = contract_name;
                        model.mobile = mobile;
                        model.qq = qq;
                        model.wx_openid = wxOpenid;
                        model.ww_code = wwCode;
                        model.id_card = idCard;
                        model.shop_url = shopUrl;
                        model.category_id = category_id;
                        model.level_id = level_id;
                        model.level_name = level_name;
                        model.start_time = start_time;
                        model.state = state;
                        model.valid = 1;
                        model.end_time = end_time;

                        bool flag;
                        if (opea == "add")
                        {
                            int ids;
                            flag = bll.Add(model, out ids);
                        }
                        else
                        {

                            flag = bll.Update(model);

                        }

                        if (flag == true)
                        {
                            if (state == 1)
                            {
                                if (model != null)
                                {
                                    authorization aumodel = new authorization { agency_id = id, start_time = start_time, end_time = end_time, valid = 1, time = DateTime.Now };
                                    aubll.Add(aumodel);//添加授权记录
                                    string bgimg = "upload/lfs_img.jpg";
                                    string uid = model.id.ToString();
                                    string bid = model.account_id.ToString();
                                    string sid = model.level_id.ToString();
                                    string uname = model.name;
                                    string ssatrdate = ((DateTime)model.start_time).ToString("yyyy/MM/dd");
                                    string senddate = ((DateTime)model.end_time).ToString("yyyy/MM/dd");
                                    string sidname = level_name;
                                    string address = shopUrl;
                                    string prams = "bgimg=" + bgimg + "&uid=" + uid + "&bid=" + bid + "&sid=" + sid + "&uname=" + uname + "&ssatrdate=" + ssatrdate + "&senddate=" + senddate + "&sidname=" + sidname + "&address=" + address + "";
                                    string url = "http://query.m12315.com/nfsImg.aspx?" + prams;
                                    System.Net.WebClient web = new System.Net.WebClient();
                                    byte[] bytes = web.DownloadData(url);
                                    string str = System.Text.Encoding.GetEncoding("UTF-8").GetString(bytes);
                                    if (str == "0" && state == 1)
                                    {
                                        string img_url = "http://m.nfs.m12315.com/tasking/" + uid + "-" + bid + ".jpeg";
                                        bll.UptSq_imgAndCode(id, "", img_url);
                                    }
                                    else
                                    {
                                        bll.UptSq_imgAndCode(id, "", "");
                                    }

                                }
                            }
                            if (flag)
                            {
                                return Json(new { MessageCode = "0" }, JsonRequestBehavior.AllowGet);
                            }
                            else
                            {
                                return Json(new { MessageCode = "100" }, JsonRequestBehavior.AllowGet);
                            }
                        }
                        else
                        {
                            return Json(new { MessageCode = "100" }, JsonRequestBehavior.AllowGet);
                        }
                    }
                    else
                    {

                        return Json(new { MessageCode = "100" }, JsonRequestBehavior.AllowGet);

                    }

                }
                else
                {

                    return Json(new { MessageCode = "50" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception)
            {

                return Json(new { MessageCode = "200" }, JsonRequestBehavior.AllowGet);
            }

        }
        #endregion


        #region 修改和新增用户，以及授权
        [HttpPost]
        public JsonResult OpeaAgency()
        {
            try
            {
                bool flag = true;
                string opea = Request["opea"] != null ? Request["opea"] : "";
                int id = Request["id"] != null ? int.Parse(Request["id"].ToString()) : 0;
                string Name = Request["Name"] != null ? Request["Name"] : "";
                string companyName = Request["companyName"] != null ? Request["companyName"] : "";
                string contract_name = Request["contract_name"] != null ? Request["contract_name"] : "";
                string mobile = Request["mobile"] != null ? Request["mobile"] : "";
                string qq = Request["qq"] != null ? Request["qq"] : "";
                string wxOpenid = Request["wxOpenid"] != null ? Request["wxOpenid"] : "";
                string wwCode = Request["wwCode"] != null ? Request["wwCode"] : "";
                string idCard = Request["idCard"] != null ? Request["idCard"] : "";
                string shopUrl = Request["shopUrl"] != null ? Request["shopUrl"] : "";
                int category_id = Request["category_id"] != null ? int.Parse(Request["category_id"]) : 0;
                int level_id = Request["level_id"] != null ? int.Parse(Request["level_id"]) : 0;
                string level_name = Request["level_name"] != null ? Request["level_name"] : "";
                DateTime start_time = Request["start_time"] != null ? DateTime.Parse(Request["start_time"]) : DateTime.Parse("1991-01-01");
                string coding = Request["coding"] != null ? Request["coding"] : "";
                int state = Request["state"] != null ? int.Parse(Request["state"].ToString()) : 1;
                int shState = Request["shState"] != null ? int.Parse(Request["shState"].ToString()) : 1;
                int share_state = Request["share_state"] != null ? int.Parse(Request["share_state"].ToString()) : 0;
  
                DateTime end_time = start_time.AddDays(90);
                AgencyBLL bll = new AgencyBLL();
                agency agencyModel = new agency();
                
                if (!bll.GetSingle(id, Name, mobile, qq, wxOpenid, wwCode, idCard, shopUrl))
                {
                    agency model = new agency();
                    model.id = id;
                    model.account_id = id;
                    model.name = Name;
                    model.company_name = companyName;
                    model.contract_name = contract_name;
                    model.mobile = mobile;
                    model.qq = qq;
                    model.wx_openid = wxOpenid;
                    model.ww_code = wwCode;
                    model.id_card = idCard;
                    model.shop_url = shopUrl;
                    model.category_id = category_id;
                    model.level_id = level_id;
                    model.level_name = level_name;
                    model.start_time = start_time;
                    model.state = state;
                    model.shState = shState;
                    model.valid = 1;
                    model.end_time = end_time;
                    model.share_state = share_state;
                   
                    account act_model = new account { user_name = mobile, user_pwd = mobile.Substring(5, 6), type = 2, IsAdmin = 0, mobile = mobile, valid = 1, time = DateTime.Now };
                    int agency_id=0;
                    if (opea == "add")
                    {
                        model.parents_id = 0;
                        flag = bll.InsertAgency(model, act_model, out agency_id);

                    }
                    else
                    {
                         
                            act_model.user_pwd = null;

                            flag = bll.UpdateAgency(model, act_model, out agency_id);
                         
                    }
                    if (flag)
                    {

                        if (state == 1)
                        {
                            string au_code = string.Empty;
                            if (opea == "add")
                            {

                                au_code = "EDJP";
                                DateTime currentTime = DateTime.Now;
                                //au_code += saleman.code.PadLeft(2, '0') + "-" + currentTime.Year + currentTime.Month.ToString().PadLeft(2, '0') + currentTime.Day.ToString().PadLeft(2, '0') + "-" + CleanInput(Guid.NewGuid().ToString("N")).Substring(0, 4);
                                au_code += "-" + CleanInput(Guid.NewGuid().ToString("N")).Substring(0, 6);
                            }
                            else
                            {
                                //编辑操作无需修改编号  待授权状态需要给授权编号
                                agency agModel = bll.GetModel(id);
                                if (string.IsNullOrEmpty(agModel.au_code))
                                {
                                    //重新给新编号
                                    au_code = "EDJP";
                                    DateTime currentTime = DateTime.Now;
                                    //au_code += saleman.code.PadLeft(2, '0') + "-" + currentTime.Year + currentTime.Month.ToString().PadLeft(2, '0') + currentTime.Day.ToString().PadLeft(2, '0') + "-" + CleanInput(Guid.NewGuid().ToString("N")).Substring(0, 4);
                                    au_code += "-" + CleanInput(Guid.NewGuid().ToString("N")).Substring(0, 6);
                                }
                                else
                                {//存在编号 就判断是否是老的编号信息 如果是 则替换成新的编号
                                    au_code = agModel.au_code;
                                    if (agModel.au_code.Substring(0, 4) != "EDJP" || agModel.au_code.Length > 11)
                                    {//不是新的编码规则
                                        //赋予新的编码规则
                                        au_code = "EDJP";
                                        DateTime currentTime = DateTime.Now;
                                        au_code += "-" + CleanInput(Guid.NewGuid().ToString("N")).Substring(0, 6);
                                        agModel.au_code = au_code;
                                        bll.UpdateAucode(au_code, agency_id);

                                    }

                                }
                                

                            }
                            AuthorizationBLL aubll = new AuthorizationBLL();
                            authorization aumodel = new authorization { agency_id = agency_id, start_time = start_time, end_time = end_time, valid = 1, time = DateTime.Now };
                            aubll.Add(aumodel);//添加授权记录
                            string bgimg = "upload/lfs_img.jpg";
                            string uid = agency_id.ToString();
                            string bid = model.account_id.ToString();
                            string sid = model.level_id.ToString();
                            string uname = model.name;
                            string ssatrdate = ((DateTime)model.start_time).ToString("yyyy/MM/dd");
                            string senddate = ((DateTime)model.end_time).ToString("yyyy/MM/dd");
                            string sidname = level_name;
                            //if (opea=="edit")
                            //{
                            //    agencyModel = bll.GetModel(id);
                            //    au_code = agencyModel.au_code;
                            //}
                          
                            string address = shopUrl;
                            string prams = "bgimg=" + bgimg + "&uid=" + uid + "&bid=" + bid + "&sid=" + sid + "&uname=" + uname + "&ssatrdate=" + ssatrdate + "&senddate=" + senddate + "&sidname=" + sidname + "&address=" + address + "&au_code=" + au_code + "";
                            string url = "http://query.m12315.com/nfsImg.aspx?" + prams;
                            System.Net.WebClient web = new System.Net.WebClient();
                            byte[] bytes = web.DownloadData(url);
                            string str = System.Text.Encoding.GetEncoding("UTF-8").GetString(bytes);

                            if (str == "0")
                            {
                                string img_url = "http://m.nfs.m12315.com/tasking/" + uid + "-" + bid + ".jpeg";
                                flag = bll.UptSq_imgAndCode(agency_id, au_code, img_url);
                            }
                        }
                        else
                        {
                            flag = bll.UptSq_imgAndCode(agency_id, "", "");
                        }
                        //if (state == 1)
                        //{
                        //    SalesManBLL salebll = new SalesManBLL();
                        //    string au_code = string.Empty;
                        //    if (opea == "add")
                        //    {
                                
                        //        au_code = "EDJP";
                        //        DateTime currentTime = DateTime.Now;
                        //        //au_code += saleman.code.PadLeft(2, '0') + "-" + currentTime.Year + currentTime.Month.ToString().PadLeft(2, '0') + currentTime.Day.ToString().PadLeft(2, '0') + "-" + CleanInput(Guid.NewGuid().ToString("N")).Substring(0, 4);
                        //        au_code += "-"+ CleanInput(Guid.NewGuid().ToString("N")).Substring(0, 6);
                        //    }
                        //    else
                        //    {
  
                               
                        //    }

                        //    AuthorizationBLL aubll = new AuthorizationBLL();
                        //     string ssatrdate=string.Empty;
                        //    string senddate =string.Empty;
                        //    if (Request["auth"] != null && !string.IsNullOrEmpty(Request["auth"].ToString()))
                        //    {
                        //        AgencyBLL bll2 = new AgencyBLL();
                        //        agency agencyModel2 = new agency();
                        //        agencyModel2 = bll2.GetModel(id);
                        //        ssatrdate = agencyModel2.start_time.Value.ToString("yyyy/MM/dd");
                        //        senddate = agencyModel2.end_time.Value.ToString("yyyy/MM/dd");
                        //        authorization aumodel = new authorization { agency_id = id, start_time = agencyModel2.start_time, end_time = agencyModel2.end_time, valid = 1, time = DateTime.Now };
                               
                        //        aubll.Add(aumodel);//添加授权记录
                        //    }
                        //    else {
                        //        ssatrdate = start_time.ToString("yyyy/MM/dd");
                        //        senddate = end_time.ToString("yyyy/MM/dd");
                        //        authorization aumodel = new authorization { agency_id = agency_id, start_time = start_time, end_time = end_time, valid = 1, time = DateTime.Now };
                        //        aubll.Add(aumodel);//添加授权记录
                        //    }
                            
                        //    string bgimg = "upload/lfs_img.jpg";
                        //    string uid = agency_id.ToString();
                        //    string bid = model.account_id.ToString();
                        //    string sid = model.level_id.ToString();
                        //    string uname = model.name;
                            
                        //    string sidname = level_name;
                        //    string address = shopUrl;
                        //    string prams = "bgimg=" + bgimg + "&uid=" + uid + "&bid=" + bid + "&sid=" + sid + "&uname=" + uname + "&ssatrdate=" + ssatrdate + "&senddate=" + senddate + "&sidname=" + sidname + "&address=" + address + "&au_code=" + au_code + "";
                        //    string url = "http://query.m12315.com/nfsImg.aspx?" + prams;
                        //    System.Net.WebClient web = new System.Net.WebClient();
                        //    byte[] bytes = web.DownloadData(url);
                        //    string str = System.Text.Encoding.GetEncoding("UTF-8").GetString(bytes);

                        //    if (str == "0")
                        //    {
                        //        string img_url = "http://m.nfs.m12315.com/tasking/" + uid + "-" + bid + ".jpeg";
                        //        flag = bll.UptSq_imgAndCode(agency_id, au_code, img_url);
                        //    }
                        //}
                        //else
                        //{
                        //    flag = bll.UptSq_imgAndCode(agency_id, "", "");
                        //}
                    }
                    if (flag)
                    {
                        return Json(new { MessageCode = "0" }, JsonRequestBehavior.AllowGet);

                    }
                    else
                    {
                        return Json(new { MessageCode = "100" }, JsonRequestBehavior.AllowGet);


                    }
                }
                else
                {

                    return Json(new { MessageCode = "50" }, JsonRequestBehavior.AllowGet);

                }

            }
            catch (Exception)
            {

                return Json(new { MessageCode = "200" }, JsonRequestBehavior.AllowGet);
            }

        }
        private static string CleanInput(string strIn)
        {
            return Regex.Replace(strIn, "[^\\d]", "");
        }
        #endregion


        #region 删除数据
        [HttpPost]
        public JsonResult delete()
        {
            try
            {
                AgencyBLL bll = new AgencyBLL();
                int id = Request["id"] != "" ? int.Parse(Request["id"]) : 0;
                if (bll.deleteAgency(id))
                {
                    return Json(new { MessageCode = "0" }, JsonRequestBehavior.AllowGet);
                }
                else
                {

                    return Json(new { MessageCode = "100" }, JsonRequestBehavior.AllowGet);
                }

            }
            catch (Exception)
            {

                return Json(new { MessageCode = "200" }, JsonRequestBehavior.AllowGet);
            }


        }
        #endregion

        #region 导出数据
        /// <summary>
        /// 导出数据
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportList()
        {

            List<AgencyExportModel> list = new List<AgencyExportModel>();
            try
            {
                AgencyBLL bll = new AgencyBLL();
                int keys = Request["keys"] != "" ? int.Parse(Request["keys"].ToString()) : -1;
                string keyName = Request["keyName"].ToString() != "" ? Request["keyName"].ToString() : "";
                int leibie = Request["leibie"].ToString() != "" ? int.Parse(Request["leibie"].ToString()) : -1;
                string shouquan = Request["shouquan"] != "" ? Request["shouquan"] : "请选择";

                list = bll.GetAgencyBycondtionList(keys, keyName, leibie, shouquan);
                new ExportUtil().ExportToCSV(list,
               new string[] { "id", "商家名称", "公司名称", "手机号码", "联系人", "QQ", "微信", "旺旺号", "身份证号", "网址", "授权时间(始)", "授权时间(止)", "授权编号", "授权图片", "类别", "级别", "状态" },
               new string[] { "id", "name", "company_name", "mobile", "contract_name", "qq", "wx_openid", "ww_code", "id_card", "shop_url", "start_time", "end_time", "au_code", "sq_img", "categoryName", "levelName", "states" }, "用户" + DateTime.Now.Year + "信息表", ".xls");
            }
            catch (Exception)
            {

            }

            return RedirectToAction("Agency");
        }
        #endregion


        #region  导入数据
        [HttpPost]
        public JsonResult ImpoertList()
        {
            try
            {
                string filepath = Request["filepath"];
                if (filepath != "")
                {
                    AgencyBLL bll = new AgencyBLL();
                    string path = System.AppDomain.CurrentDomain.BaseDirectory + filepath;
                    List<agency> list = new List<agency>();
                    DataTable dt = ExportUtil.ImportBoardInfo(path);
                    if (dt.Rows.Count == 0)
                    {
                        return Json(new { MessageCode = "100" }, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        foreach (DataRow dtr in dt.Rows)
                        {
                            agency ag = new agency();
                            ag.name = dtr["商家名称"].ToString();
                            ag.company_name = dtr["公司名称"].ToString();
                            ag.mobile = dtr["手机号码"].ToString();
                            ag.contract_name = dtr["联系人"].ToString();
                            ag.qq = dtr["QQ"].ToString();
                            ag.wx_openid = dtr["微信"].ToString();
                            ag.ww_code = dtr["旺旺号"].ToString();
                            ag.id_card = dtr["身份证号"].ToString();
                            ag.shop_url = dtr["网址"].ToString();
                            list.Add(ag);
                        }
                        List<agency> lists = new List<agency>();
                        bool flag = true;
                        foreach (agency ag in list)
                        {
                            if (bll.GetSingle(0, ag.name, ag.mobile, ag.qq, ag.wx_openid, ag.ww_code, ag.id_card, ag.shop_url))
                            {
                                //agency ags = new agency();
                                //ags.name = ag.name;
                                //ags.company_name = ag.company_name;
                                //ags.mobile = ag.mobile;
                                //ags.contract_name = ag.contract_name;
                                //ags.qq = ag.qq;
                                //ags.wx_openid = ag.qq;
                                //ags.ww_code = ag.ww_code;
                                //ags.id_card = ag.id_card;
                                //ags.shop_url = ag.shop_url;
                                lists.Add(ag);
                            }
                            else
                            {
                                account act = new account();
                                act.user_name = ag.mobile;
                                act.user_pwd = ag.mobile.Length == 11 ? ag.mobile.Substring(5, 6) : "123456";
                                act.IsAdmin = 0;
                                act.type = 2;
                                act.mobile = ag.mobile;
                                act.valid = 1;
                                act.time = DateTime.Now;
                                int id;
                                ag.valid = 1;
                                ag.parents_id = 0;
                                ag.state = 0;
                                flag = bll.InsertAgency(ag, act, out id);

                            }
                        }
                        if (lists.Count == 0)
                        {
                            if (flag == true)
                            {
                                return Json(new { MessageCode = "0" }, JsonRequestBehavior.AllowGet);
                            }
                            else
                            {
                                return Json(new { MessageCode = "100" }, JsonRequestBehavior.AllowGet);

                            }

                        }
                        else
                        {
                            int count = list.Count - lists.Count;
                            return Json(new { MessageCode = "50", count = count, list = lists }, JsonRequestBehavior.AllowGet);

                        }

                    }
                }
                else
                {
                    return Json(new { MessageCode = "100" }, JsonRequestBehavior.AllowGet);

                }

            }
            catch (Exception)
            {

                return Json(new { MessageCode = "200" }, JsonRequestBehavior.AllowGet);
            }


        }
        #endregion
    }
}
